package org.hiucung.hlsdownloader.bean

/**
 * 加密Key数据类
 */
data class EncryptionKey(
    val method: String,
    val uri: String? = null,
    val iv: String? = null,
    val keyFormat: String? = null,
    val keyFormatVersions: String? = null
) {
    /**
     * 获取IV的字节数组（支持16进制和十进制格式）
     */
    fun getIvBytes(): ByteArray? {
        return iv?.let {
            if (it.startsWith("0x") || it.startsWith("0X")) {
                // 16进制格式
                hexStringToByteArray(it.substring(2))
            } else {
                // 尝试解析为16字节的IV（可能是十进制字符串）
                try {
                    val longValue = it.toLong()
                    ByteArray(16) { index ->
                        ((longValue shr (8 * (15 - index))) and 0xFF).toByte()
                    }
                } catch (e: Exception) {
                    null
                }
            }
        }
    }

    /**
     * 16进制字符串转字节数组
     */
    private fun hexStringToByteArray(hex: String): ByteArray {
        require(hex.length % 2 == 0) { "十六进制字符串长度必须为偶数" }
        return hex.chunked(2).map { it.toInt(16).toByte() }.toByteArray()
    }
}
